﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using MesProjectWinform.Equipment.Output;
using MesProjectWinform.Equipment.Request;
using MesProjectWinform.Public;
using MesProjectWinform.Public.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace MesProjectWinform.Equipment.Form.ProjectMaintenance
{
    /// <summary>
    /// 项目维护显示列表窗体
    /// </summary>
    public partial class ProjectMaintenanceForm : DevExpress.XtraEditors.XtraForm
    {
        public ProjectMaintenanceForm()
        {
            InitializeComponent();
        }
        private int pageIndex = 1; // 当前页码
        private int pageSize = 3; // 每页显示的记录数
        private int totalCount = 0; // 总记录数
        private int totalPages = 0;// 总页数


        /// <summary>
        /// 获取项目维护列表并刷新
        /// </summary>
        /// <returns></returns>
        private async Task ReInit(string projectMaintenanceCode = "", string projectMaintenanceName = "", string criterion = "")
        {
            List<ProjectMaintenanceOutput> projectMaintenanceOutputs = new List<ProjectMaintenanceOutput>();
            //如果有条件，则进行条件查询
            if (string.IsNullOrEmpty(criterion) || string.IsNullOrEmpty(projectMaintenanceCode) || string.IsNullOrEmpty(projectMaintenanceName)) 
            {
                projectMaintenanceOutputs = await GetProjectMaintenanceList();
            }

            projectMaintenanceOutputs = await GetProjectMaintenanceByCondition(projectMaintenanceCode, projectMaintenanceName, criterion);

            gridControl1.DataSource = projectMaintenanceOutputs;

            var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (gridView != null)
            {
                gridView.Columns.Clear();

                gridView.Columns.AddVisible("Id", "编号");
                gridView.Columns.AddVisible("ProjectMaintenanceCode", "项目维护编码");
                gridView.Columns.AddVisible("ProjectMaintenanceName", "项目维护名称");
                //gridView.Columns.AddVisible("CheckoutWay", "检出方式");
                gridView.Columns.AddVisible("CheckoutWayText", "检出方式");
                gridView.Columns.AddVisible("ValueType", "值类型");
                gridView.Columns.AddVisible("ProjectMaintenanceMinNum", "最小值");
                gridView.Columns.AddVisible("ProjectMaintenanceMaxNum", "最大值");
                gridView.Columns.AddVisible("Criterion", "判定基准");
                gridView.Columns.AddVisible("CreatedBy", "创建人");
                gridView.Columns.AddVisible("UpdatedBy", "更新人");
                // 为日期时间列设置格式
                var createdTimeColumn = gridView.Columns.AddVisible("CreatedTime", "创建时间");
                var updatedTimeColumn = gridView.Columns.AddVisible("UpdatedTime", "更新时间");
                // 设置日期时间格式为 yyyy-MM-dd HH:mm:ss
                createdTimeColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                createdTimeColumn.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";

                updatedTimeColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                updatedTimeColumn.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
            }
            // 如果还没有“操作”列，则添加操作列（包含删除和编辑按钮）
            if (gridView.Columns["操作"] == null)
            {
                // 添加“操作”列
                var col = gridView.Columns.AddVisible("操作", "操作");

                // 设置为非绑定列（自定义按钮）
                col.UnboundType = DevExpress.Data.UnboundColumnType.Object;

                // 始终显示按钮
                col.ShowButtonMode = DevExpress.XtraGrid.Views.Base.ShowButtonModeEnum.ShowAlways;

                // 创建按钮编辑器
                RepositoryItemButtonEdit buttonEdit = new RepositoryItemButtonEdit();
                buttonEdit.TextEditStyle = TextEditStyles.HideTextEditor; // 隐藏文本框，仅显示按钮
                buttonEdit.Buttons.Clear();
                // 添加“删除”按钮
                buttonEdit.Buttons.Add(new EditorButton(ButtonPredefines.Glyph)
                {
                    Caption = "删除",
                    Kind = ButtonPredefines.Glyph,
                    // 可选：设置按钮图片为 null，仅显示文字
                    ImageOptions = { Image = null } // 不显示图片
                });
                // 添加“编辑”按钮
                buttonEdit.Buttons.Add(new EditorButton(ButtonPredefines.Glyph)
                {
                    Caption = "编辑",
                    Kind = ButtonPredefines.Glyph,
                    // 可选：设置按钮图片为 null，仅显示文字
                    ImageOptions = { Image = null } // 不显示图片
                });
                // 按钮点击事件处理
                buttonEdit.ButtonClick += async (s, a) =>
                {
                    // 获取当前选中的行
                    var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
                    var rowHandle = view.FocusedRowHandle;
                    var row = view.GetRow(rowHandle) as ProjectMaintenanceOutput;
                    if (row != null)
                    {
                        if (a.Button.Index == 0)// 删除按钮
                        {
                            Console.WriteLine($"删除按钮被点击，ID: {row.Id}"); // 调试信息
                            long id = row.Id;
                            // 调用删除方法
                            await DeletedProjectMaintenance(id);
                        }
                        else if (a.Button.Index == 1)// 编辑按钮
                        {
                            // 弹出编辑窗口，回显数据并支持修改
                            using (var client = new HttpClient())
                            {
                                // 获取当前设备台账详细信息
                                var response = client.GetStringAsync($"http://47.110.243.157:5229/api/ProjectMaintenance/GetProjectMaintenanceValue?id={row.Id}").Result;
                                var projectMaintenance = JsonConvert.DeserializeObject<ApiResult<ProjectMaintenanceOutput>>(response);
                                projectMaintenance.Data.Id = row.Id;
                                ProjectMaintenanceEditForm projectMaintenanceEditForm = new ProjectMaintenanceEditForm(); // 实例化编辑窗体
                             
                                // 回显数据
                                projectMaintenanceEditForm.GetProjectMaintenanceData(projectMaintenance.Data);
                                // 显示编辑窗口
                                var result = projectMaintenanceEditForm.ShowDialog();
                                if (result == DialogResult.OK)
                                {
                                    // 编辑成功后，刷新设备台账列表
                                    await ReInit();
                                }
                            }
                        }
                    }
                };
                // 将按钮编辑器赋给“操作”列
                col.ColumnEdit = buttonEdit;
            }
        }

        /// <summary>
        /// 根据条件获取项目维护列表
        /// </summary>
        /// <param name="projectMaintenanceCode"></param>
        /// <param name="projectMaintenanceName"></param>
        /// <param name="criterion"></param>
        private async Task<List<ProjectMaintenanceOutput>> GetProjectMaintenanceByCondition(string projectMaintenanceCode, string projectMaintenanceName, string criterion)
        {
            try
            {
                using (var clien = new HttpClient())
                {
                    // 构造查询参数字符串，包含分页参数
                    string queryParams = $"PageIndex={pageIndex}&PageSize={pageSize}";
                    // 如果有条件，则添加条件查询参数

                    if (!string.IsNullOrEmpty(projectMaintenanceCode))
                    {
                        queryParams+= $"&ProjectMaintenanceCode={projectMaintenanceCode}";
                    }

                    if (!string.IsNullOrEmpty(projectMaintenanceName))
                    {
                        queryParams += $"&ProjectMaintenanceName={projectMaintenanceName}";
                    }

                    if (!string.IsNullOrEmpty(criterion))
                    {
                        queryParams += $"&Criterion={criterion}";
                    }

                    var response = await clien.GetStringAsync($"http://47.110.243.157:5229/api/ProjectMaintenance/GetProjectMaintenanceList?{queryParams}");
                    return JsonConvert.DeserializeObject<ApiPaging<ProjectMaintenanceOutput>>(response).PageData;

                }
            }
            catch (Exception ex)
            {
                // 查询过程中发生异常，弹窗提示错误信息，并返回空列表
                MessageBox.Show($"查询出错：{ex.Message}");
                return new List<ProjectMaintenanceOutput>();
            }
        }

        /// <summary>
        /// 项目维护获取列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ProjectMaintenanceForm_Load(object sender, EventArgs e)
        {
            await ReInit();
        }

        /// <summary>
        /// 获取项目维护列表
        /// </summary>
        /// <returns></returns>
        private async Task<List<ProjectMaintenanceOutput>> GetProjectMaintenanceList()
        {
            using (var client = new HttpClient())
            {
                var response = await client.GetStringAsync("http://47.110.243.157:5229/api/ProjectMaintenance/GetProjectMaintenanceList");
                var result = JsonConvert.DeserializeObject<ApiPaging<ProjectMaintenanceOutput>>(response);
                totalCount = result.TotalCount;
                totalPages = (int)Math.Ceiling((totalCount * 1.0) / pageSize);
                return result.PageData;
            }
        }

        /// <summary>
        /// 新增项目维护点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddProjectMaintenanceButton1_Click(object sender, EventArgs e)
        {
            // 创建项目维护添加表单的实例
            ProjectMaintenanceAddForm projectMaintenanceAddForm = new ProjectMaintenanceAddForm();
            // 显示项目维护添加表单对话框
            projectMaintenanceAddForm.ShowDialog();

            // 如果对话框的结果为确定，则调用项目维护表单加载方法
            if (projectMaintenanceAddForm.DialogResult == DialogResult.OK)
            {
                ProjectMaintenanceForm_Load(sender, e);
            }
        }


        /// <summary>
        /// 删除项目维护点击事件
        /// </summary>
        private async Task DeletedProjectMaintenance(long id)
        {
            try
            {
                // 添加确认对话框
                DialogResult result = XtraMessageBox.Show("确定要删除此项目维护记录吗？", "确认删除",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result != DialogResult.Yes)
                    return;

                // 使用与其他API调用相同的基础URL
                using (var client = new HttpClient())
                {
                    var response = await client.DeleteAsync($"http://47.110.243.157:5229/api/ProjectMaintenance/DeleteProjectMaintenance?id={id}");

                    if (response.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        await ReInit(); // 刷新数据
                    }
                    else
                    {
                        string errorContent = await response.Content.ReadAsStringAsync();
                        XtraMessageBox.Show($"删除失败！状态码：{response.StatusCode}，错误信息：{errorContent}",
                            "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"删除操作出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        /// <summary>
        /// 重置按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ResetButton3_Click(object sender, EventArgs e)
        {
            ProjectMaintenanceCode.Text = "";
            ProjectMaintenanceName.Text = "";
            Criterion.Text = "";
        }

        /// <summary>
        /// 查询按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void SelectQueryButton2_Click(object sender, EventArgs e)
        {
            // 获取查询条件
            string projectMaintenanceCode = ProjectMaintenanceCode.Text.Trim();
            string projectMaintenanceName = ProjectMaintenanceName.Text.Trim();
            string criterion = Criterion.Text.Trim();
            await ReInit(projectMaintenanceCode, projectMaintenanceName, criterion);

            var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (gridView != null)
            {
                //提示查询到的数量
                var totalCount = gridView.DataRowCount;
                XtraMessageBox.Show($"查询到{totalCount}条记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 上一页按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void PrevPageButton5_Click(object sender, EventArgs e)
        {
            if (pageIndex <= 1)
            {
                XtraMessageBox.Show("已经是第一页了！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            pageIndex -= 1;
            await ReInit();
        }

        /// <summary>
        /// 下一页按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void NexttPageButton4_Click(object sender, EventArgs e)
        {
            if (pageIndex >= totalPages)
            {
                XtraMessageBox.Show("已经是最后一页了！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            pageIndex += 1;
            await ReInit();
        }
    }
}